/*
    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License along
    with this program; if not, write to the Free Software Foundation, Inc.,
    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

*/

#include "videodevice.h"
#include "videodeviceinformation.h"

#include <linux/videodev2.h>
#include <sys/ioctl.h>

#include <QFile>
#include <QDebug>
class _VideoDevicePrivate {
  public:
    QFile *device;
};

VideoDevice::VideoDevice(QString device, QObject* parent): QObject(parent)
{
  this->d=new _VideoDevicePrivate();
  this->d->device=new QFile(device, this);
}

VideoDevice::~VideoDevice()
{
  delete d;
}

void VideoDevice::openDevice()
{
    if(! device()->open(QIODevice::ReadWrite)) {
    qDebug() << "Could not open video device: " << device()->errorString() << " (" << device()->error() << ")";
//     QThread::exit(1);
    return;
  }
}

void VideoDevice::closeDevice()
{
  device()->close();
}


QFile* VideoDevice::device()
{
  return d->device;
}

void VideoDevice::initialize()
{
  qDebug() << "Initializing " << d->device->fileName();
  d->device->open(QIODevice::ReadWrite);
  v4l2_capability capabilities;
  v4l2_fmtdesc formats;
  formats.index=0;
  formats.type=V4L2_BUF_TYPE_VIDEO_CAPTURE;
  ioctl(d->device->handle(), VIDIOC_QUERYCAP, &capabilities);
  ioctl(d->device->handle(), VIDIOC_ENUM_FMT, &formats);

  qDebug() << "format: " << (char*) formats.description << " (" << QString::number(formats.pixelformat, 16) << ")";
  qDebug() << (VideoDeviceInformation::from(&capabilities, &formats, this))->debugInformation();

  
}


#include "videodevice.moc"
